<template>
  <el-dialog
    @open="handleQuery"
    :title="dialogTitle"
    v-model="showDialog"
    left
    destroy-on-close="true"
    :append-to-body="true"
    class="drag-dialog small-padding-dialog"
    width="90%"
    @close="close"
  >
    <el-tabs v-model="activeName" type="border-card">
      <el-tab-pane label="音频库" name="library">
        <ContentWrap>
          <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
            <el-table-column type="selection" label="id" align="center" key="id" prop="id" />
            <el-table-column label="ID" align="center" prop="id" :width="60" />
            <el-table-column prop="name" label="名称" align="center" />
            <el-table-column align="center" prop="fileSize" label="大小" />
            <el-table-column prop="ext" label="格式" align="center" />
          </el-table>
          <!-- 分页 -->
          <Pagination
            v-model:limit="queryParams.pageSize"
            v-model:page="queryParams.pageNo"
            :total="total"
            @pagination="getList"
          />
        </ContentWrap>
      </el-tab-pane>
      <el-tab-pane label="本地上传" name="local">
        <el-upload
          ref="upload"
          :auto-upload="false"
          class="upload-demo"
          :show-file-list="false"
          :accept="AudioFormat"
          v-model:file-list="fileList"
          action="#"
          drag
          multiple="true"
          :on-change="handleChange"
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">拖拽文件到这里或者<em>点击上传</em></div>
          <div class="el-upload__tip">
            支持格式：{{ AudioFormatStr }}，音频大小不超过{{ AudioSize }}M
          </div>
        </el-upload>
        <div style="margin-top: 10px" v-if="saved">
          <div class="block-left" id="left">
            <el-form :model="audioForm" label-width="80px" ref="audioFormRef">
              <el-row>
                <el-col :span="12">
                  <el-form-item
                    label="资源标题"
                    :rules="{ required: true, trigger: ['blur', 'change'], message: '请填写资源标题' }"
                    prop="name"
                  >
                    <el-input v-model="audioForm.name" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="批次编号" prop="batch">
                    <el-input v-model="audioForm.batch" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="DOI">
                    <el-input v-model="audioForm.doi" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="音频来源">
                    <el-input v-model="audioForm.source" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="音频标签">
                    <el-select v-model="audioForm.label" placeholder="请选择音频标签">
                      <el-option
                        v-for="item in labelList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="音频分类">
                    <el-select v-model="audioForm.classify" placeholder="请选择音频分类">
                      <el-option
                        v-for="item in classifyList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="作者">
                    <el-input v-model="audioForm.author" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="用途">
                    <el-input v-model="audioForm.useTo" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="发布时间">
                    <el-date-picker
                      v-model="audioForm.releaseTime"
                      type="date"
                      placeholder="请选择发布时间"
                      :disabled-date="disabledDate"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="密级">
                    <el-select v-model="audioForm.secret" placeholder="请选择密级">
                      <el-option
                        v-for="item in secretList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="拍摄时间">
                    <el-date-picker
                      v-model="audioForm.captureTime"
                      type="date"
                      placeholder="请选择拍摄时间"
                      :disabled-date="disabledDate"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="相关地点">
                    <el-input v-model="audioForm.place" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="描述">
                    <el-input type="textarea" v-model="audioForm.remark" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
          <div class="block-right">
            <el-progress
              type="dashboard"
              v-if="!audioForm.url"
              :percentage="percentage"
              width="200"
              :indeterminate="true"
            >
              <template #default="{ percentage }">
                <span class="percentage-value">{{ percentage }}%</span>
                <span class="percentage-label">{{ uploadTitle }}</span>
              </template>
            </el-progress>
            <audio v-if="audioForm.url" :src="audioForm.url" controls></audio>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="define">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { AudioFormatStr, AudioSize, AudioFormat } from '@/utils/config'
import {ref,reactive} from "vue"
import * as AudioApi from "@/api/audio";
import * as metaApi from "@/api/meta";
import {UploadFiles, UploadProps} from "element-plus";
import {generateUUID} from "@/utils";
import * as audioApi from "@/api/audio";
import {addAudio} from "@/api/meta";

const activeName = ref('local')
const showDialog = ref(false)
const queryFormRef = ref<any>()
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const fileList = ref<UploadFiles>([])
const saved = ref(false)
const audioForm = ref({})
const videoHeight = ref(0)
const uploadTitle = ref('')
const showProgress = ref(true)

const classifyList = ref([])
const labelList = ref([])
const showImageUploadDialogFlag = ref(false)
const dialogTitle = ref('音频上传')
// 分块大小20MB
const chunkSize = 1024 * 1024 * 20

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  type: 10,
  name: null,
  createTime: []
})

const open = () => {
  showDialog.value = true
}
const close = () => {
  showDialog.value = false
}

const percentage = ref(0)

const handleChange: UploadProps['onChange'] = async (uploadFile, uploadFiles) => {
  saved.value = true
  //uploadTitle.value = '正在计算文件MD5'
  let md5 = generateUUID()
  let fileName = uploadFile.name
  uploadFile.md5 = md5
  const fileSize = uploadFile.size || 0
  let chunkTotals = Math.ceil(fileSize / chunkSize)
  let percents = 0
  uploadTitle.value = '正在上传'
  if (chunkTotals > 1) {
    for (
      let chunkNumber = 0, start = 0;
      chunkNumber < chunkTotals;
      chunkNumber++, start += chunkSize
    ) {
      let end = Math.min(fileSize, start + chunkSize)
      // uploadFile.raw这个是element plus 中 el-upload的自己上传的文件就放在这个raw里面，可以console.log(uploadFile)看一下
      // 加 ？是因为ts语法提示“uploadFile.raw”可能为“未定义”，加了这个就不过有报错了
      const files = uploadFile.raw?.slice(start, end)
      let form = new FormData()
      form.append('chunkNumber', chunkNumber + 1)
      form.append('chunkTotal', chunkTotals)
      form.append('fileName', uploadFile.name)
      form.append('file', files)
      form.append('fileMD5', md5)
      const result = await audioApi.uploadChunk(form)
      if (result.data) {
        console.log(chunkTotals)
        percents = percents + Number(((1 / chunkTotals) * 100).toFixed(0))
        if (chunkNumber == chunkTotals - 1) {
          percents = 100
          uploadTitle.value = '上传成功'
        }
        uploadFile.percentage = percents
        percentage.value = percents
      }
    }
    let video = await audioApi.merge(md5, chunkTotals, uploadFile.size, fileName.split('.').pop())
    showProgress.value = false
    audioForm.value = video
  } else if (chunkTotals == 1) {
    let form = new FormData()
    form.append('file', uploadFile.raw)
    const result = await audioApi.upload(form)
    console.log(result)
    showProgress.value = false
    audioForm.value = result.data
  }
  audioForm.value.name = uploadFile.name
}

const selectedItems = ref([])
const handleSelectionChange = (row) => {
  selectedItems.value = row
}

const getList = async () => {
  loading.value = true
  try {
    const data = await AudioApi.page(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const handleQuery = () => {
  getList()
}

const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

const refresh: any = inject('getList')

const props = defineProps({
  dataId: String,
  fieldId: String
})

const define = async () => {
  if (activeName.value == 'local') {
    const audios = []
    audios.push(audioForm.value)
    await metaApi.addAudio(props.dataId, props.fieldId, audios)
  } else if (activeName.value == 'library') {
    await metaApi.addAudio(props.dataId, props.fieldId, selectedItems.value)
  }
  close()
  refresh()
}

defineExpose({
  open
})

</script>
<style lang="scss" scoped>
.block-left {
  display: inline-block;
  width: 70%;
  padding: 30px 20px;
  text-align: center;
  vertical-align: top;
  border-right: solid 1px var(--el-border-color);
  box-sizing: border-box;
}

.block-right {
  display: inline-block;
  width: 30%;
  padding: 30px 20px;
  text-align: center;
  vertical-align: top;
  border-right: solid 1px var(--el-border-color);
  box-sizing: border-box;
}

.dialog-footer {
  text-align: center;
}

.body {
  margin: 0;
}

.demo-image__error .block {
  display: inline-block;
  width: 20%;
  height: 330px;
  padding: 30px 20px;
  text-align: center;
  vertical-align: top;
  border-right: solid 1px var(--el-border-color);
  box-sizing: border-box;
}

.demo-image__error .block .more {
  float: right;
  color: #8c8a8a;
}

.demo-image__error .demonstration {
  display: block;
  margin-top: 10px;
  margin-bottom: 20px;
  font-size: 14px;
  color: var(--el-text-color-secondary);
  text-align: left;
}

.demo-image__error .datetime {
  display: block;
  margin-top: 10px;
  font-size: 14px;
  color: #666;
  text-align: left;
}

.demo-image__error .checkbox {
  display: block;
  margin-bottom: 10px;
  font-size: 14px;
  text-align: left;
}

.demo-image__error .el-image {
  width: 100%;
  height: 100%;
  max-width: 300px;
  max-height: 200px;
}

.demo-image__error .image-slot {
  display: flex;
  width: 100%;
  height: 100%;
  font-size: 30px;
  color: var(--el-text-color-secondary);
  background: var(--el-fill-color-light);
  justify-content: center;
  align-items: center;
}

.demo-image__error .image-slot .el-icon {
  font-size: 30px;
}

.option {
  display: flex;
  float: right;
  color: #8c8e91;
  cursor: pointer;
  align-items: center;
}

.videoBox {
  //  object-fit: fill;
  width: 100%;
  background-image: url('@/assets/svgs/login-bg.svg');
  background-repeat: no-repeat;
  background-size: contain;
}
</style>
